const pageNav = document.getElementsByClassName('page-nav')[0]
const windowPopUp = document.getElementsByClassName('window-pop-up')[0]
const addBtn = document.getElementsByClassName('add-btn')[0]

const form = document.forms[0]
const userCount = +form['userCount'].value
const limit = +form['limit'].value
const page = +form['page'].value

const SERVICE_API_URL_PREFIX = 'http://192.168.1.105:3001/'  // 'http://localhost:3001/'

renderNav()
addBtn.addEventListener('click', addUser, false)

form.addEventListener(('click'), function(e) {
  const targetEle = e.target
  const regexp = /^([\S|\s]+)-btn/
  const classNameStr = targetEle.className
  const matchTemp = classNameStr.match(regexp)
  if(matchTemp) {
    const operateType = matchTemp[1]
    const fatherEle = targetEle.parentElement
    const { userId } = fatherEle.dataset //获取到了user_id
    switch(operateType) {
      case 'edit':
        const passwordEle = fatherEle.previousElementSibling
        const usernameEle = passwordEle.previousElementSibling
        editUserById(userId, {nickname: usernameEle.value, password: passwordEle.value})
        break;
      case 'unlock':
        console.log(userId)
        lock(userId, false)
        break;
      case 'lock':
        lock(userId, true)
        break;
      case 'add-active':
        windowPopUp.style.display = 'block'
    }
  }
})

//修改用户属性
function editUserById(userId, {nickname, password}) { 
  $Ajax({
    url:  SERVICE_API_URL_PREFIX + 'back_api/v1.0/users/' + userId,
    method: 'PUT', 
    data: {
      UPDATE: {nickname, password}
    }, 
    dataType: 'application/json; charset=utf-8',
    success(res) {
      try {
        res = JSON.parse(res)
        if(res.status === 'success'){
          // alert('修改成功')
          reloadPage()
        } 
      }catch(e) {
        console.log(e.message)
      }
    }
  })
}

//是否锁定用户
function lock(userId, isToLock) {
  $Ajax({
    url: SERVICE_API_URL_PREFIX + 'back_api/v1.0/users/' + userId,
    method: 'PUT', 
    data: {
      UPDATE: {status: isToLock ? '0' : '1'}
    }, 
    dataType: 'application/json; charset=utf-8',
    success(res) {
      try {
        res = JSON.parse(res)
        let message = isToLock ? '锁定成功' : '解锁成功'
        if(res.status === 'success'){
          // alert(message)
          reloadPage()
        } 
      }catch(e) {
        console.log(e.message)
      }
    }
  })
}

//渲染nav
function renderNav() { 
  const pages = Math.ceil(userCount / limit)
  let pageNavInnerHTML = ''
  for(let i=1; i<=pages; i++) {
    pageNavInnerHTML += `
    <a class="nav-item${page === i ? ' active' : ''}" href="./user?page=${i}&limit=${limit}">${i}</a>
    `
  }
  pageNav.innerHTML = pageNavInnerHTML
}

//添加用户
function addUser() {
  $Ajax({
    url: SERVICE_API_URL_PREFIX + 'back_api/v1.0/users',
    method: 'POST', 
    data: {
      nickname: nickname.value,
      password: password.value
    }, 
    dataType: 'application/json; charset=utf-8',
    success(res) {
      try {
        res = JSON.parse(res)
        if(res.status === 'success'){
          reloadPage()
        }else {
          alert(res.message)
        }
      }catch(e) {
        console.log(e.message)
      }
    }
  })
}
//刷新页面
function reloadPage() {
  location.reload(true)
}
